import axios from 'axios';

const service = axios.create({
    baseURL: '/',
    // baseURL: WEBPATH.NODE_ENV == 'development'?WEBPATH.WEB_API_DEVELOPMENT+'/index.php?s=':WEBPATH.WEB_API_PRODUCTION+'/index.php?s=',
    timeout: 90000,
    withCredentials: true
});

service.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    } 
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            if (response.data.code == -1) {
                window.location.href='#/login'
            }
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

/**
 * post 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        service.post(url, data).then(
            response => {
                resolve(response.data);
            },
            err => {
                const error=err?JSON.stringify(err):'网络错误'
                reject(error);
            }
        );
    });
}
/**
 * get 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, data = {}) {
    return new Promise((resolve, reject) => {
        service.get(url, { params: data }).then(
            response => {
                resolve(response.data);
            },
            err => {
                const error=err?JSON.stringify(err):'网络错误'
                reject(error);
            }
        );
    });
}

export default service;
